package com.softWang.system.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.softWang.common.base.BaseServiceMy;
import com.softWang.common.dataPermission.aop.DataPermission;
import com.softWang.common.exception.LogicException;
import com.softWang.common.tenent.aop.TenantIgnore;
import com.softWang.system.controller.vo.systemUsers.*;
import com.softWang.system.utils.AuthenticateProvider;
import com.softWang.system.constants.SystemParamterContants;
import com.softWang.system.mapper.*;
import com.softWang.system.po.*;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SystemUsersService extends BaseServiceMy<SystemUsers> {
    @Resource
    private SystemParameterService systemParameterService;
    @Resource
    private SystemUsersMapper systemUsersMapper;

    @Resource
    private SystemUserRoleMapper systemUserRoleMapper;
    @Resource
    private SystemRolesMapper systemRolesMapper;
    @Resource
    private SystemDeptsMapper systemDeptsMapper;

    /**
     * 分页条件查询
     * @param param
     * @return
     */
    //@DataPermission(includeTableAlias = {"u"})
    public List<SystemUserQueryAllResult> queryall(SystemUserQueryAllParam param){
        param.startPage();
        List<SystemUserQueryAllResult> users=systemUsersMapper.queryall(param);
        return users;
    }

    /**
     * 插入用户
     * @param user 用户信息
     * @return 用户id
     */
    @Transactional
    public Long add(SystemUsers user) {
        // 验证登录名是否有效
        if (user.getLoginName() == null || user.getLoginName().trim().isEmpty()) {
            throw new LogicException("登录名称无效！");
        }
        // 验证登录名唯一性
        Long userNum = systemUsersMapper.selectCount(new LambdaQueryWrapper<SystemUsers>().eq(SystemUsers::getLoginName, user.getLoginName()));
        if (userNum > 0) {
            throw new LogicException("登录名已存在!");
        }
        // 添加用户

        // 设置密码
        SystemParameter passwordP = systemParameterService.getByKey(SystemParamterContants.USER_DEFALUT_PASSWORD);
        if(passwordP==null){
            throw new LogicException("无法获得参数:"+SystemParamterContants.USER_DEFALUT_PASSWORD);
        }
        String encPassword= AuthenticateProvider.encodeLoginPasswordOnMd5(passwordP.getPvalue(), user.getLoginName());
        user.setPassword(encPassword);
        systemUsersMapper.insert(user);


        // 添加用户角色关联关系表
        List<Long> roleIds = user.getRoleIds();
        if (null != roleIds && roleIds.size() != 0) {
            for (Long roleId : roleIds) {
                SystemUserRole userrole = new SystemUserRole();
                userrole.setRoleid(roleId);
                userrole.setUserid(user.getId());
                systemUserRoleMapper.insert(userrole);
            }
        }
        return user.getId();
    }

    /**
     * 修改用户
     * @param user
     * @return
     */
    @Transactional
    public Long edit(SystemUsers user) {
        //先判断是否系统超管，超管不可修改
        SystemUsers old = systemUsersMapper.selectById(user.getId());
        if(old == null){
            throw new LogicException("用户不存在");
        }
        if(old.getType() == SystemUsers.UserType.SUPPERADMIN.getCode()){
            throw new LogicException("系统超管，不可修改");
        }
        // 登录名进行修改
        if(!user.getLoginName().equals(old.getLoginName())){
            // 验证登录名是否有效
            if (user.getLoginName() == null || user.getLoginName().trim().isEmpty()) {
                throw new LogicException("登录名称无效！");
            }
            // 验证登录名唯一性
            Long userNum = systemUsersMapper.selectCount(new LambdaQueryWrapper<SystemUsers>()
                    .eq(SystemUsers::getLoginName, user.getLoginName())
                    .ne(SystemUsers::getId, user.getId()));
            if (userNum > 0) {
                throw new LogicException("登录名已存在!");
            }
            // 设置密码
            SystemParameter passwordP = systemParameterService.getByKey(SystemParamterContants.USER_DEFALUT_PASSWORD);
            if(passwordP==null){
                throw new LogicException("无法获得参数:"+SystemParamterContants.USER_DEFALUT_PASSWORD);
            }
            String encPassword= AuthenticateProvider.encodeLoginPasswordOnMd5(passwordP.getPvalue(), user.getLoginName());
            user.setPassword(encPassword);
        }else{
            user.setPassword(old.getPassword());
        }
        // 修改用户表
        systemUsersMapper.updateById(user);

        // 修改用户角色关系表
        systemUserRoleMapper.delete(Wrappers.lambdaQuery(SystemUserRole.class)
                .eq(SystemUserRole::getUserid, user.getId()));
        List<Long> roleIds = user.getRoleIds();
        if (null != roleIds && roleIds.size() != 0) {
            for (Long roleId : roleIds) {
                SystemUserRole userrole = new SystemUserRole();
                userrole.setRoleid(roleId);
                userrole.setUserid(user.getId());
                systemUserRoleMapper.insert(userrole);
            }
        }

        return user.getId();
    }

    /**
     * 获取详情
     * @param id 用户id
     * @return void
     */
    public SystemUserDetailResult getById(Long id) {
        SystemUserDetailResult result = new SystemUserDetailResult();
        SystemUsers user = systemUsersMapper.selectById(id);
        if (user != null) {
            //复制属性
            BeanUtils.copyProperties(user, result);
            //获取部门名称
            if (user.getDeptid() != null) {
                SystemDepts dept = systemDeptsMapper.selectById(user.getDeptid());
                result.setDeptName(dept.getDname());
            }
            //获取角色名称
            List<SystemUserRole> userRoles = systemUserRoleMapper.selectList(Wrappers.lambdaQuery(SystemUserRole.class)
                    .eq(SystemUserRole::getUserid, id));
            if(userRoles != null && userRoles.size() != 0){
                List<Long> roleIds = userRoles.stream().map(SystemUserRole::getRoleid).collect(Collectors.toList());
                List<SystemRoles> roles = systemRolesMapper.selectBatchIds(roleIds);
                String roleNames = roles.stream().map(SystemRoles::getRname).collect(Collectors.joining(","));
                result.setRoleIds(roleIds);
                result.setRoleNames(roleNames);
            }
            //获取创建人
            SystemUsers cuser = systemUsersMapper.selectById(user.getCuser());
            result.setCuserName(cuser.getUname());
        }
        return result;
    }


    /**
     * 删除用户
     * @param ids 用户id列表
     * @return void
     */
    @Transactional
    public void del(List<Long> ids) {
        systemUsersMapper.deleteByIds(ids);
        //删除用户角色关联关系表
        systemUserRoleMapper.delete(Wrappers.lambdaQuery(SystemUserRole.class).in(SystemUserRole::getUserid, ids));
    }


    /**
     * 获取登录名的数量
     * @param param
     * @return
     */
    @TenantIgnore
    public Long countByLoginName(SystemUserCheckNameParam param) {
        // 验证登录名唯一性
        Long userNum = systemUsersMapper.selectCount(new LambdaQueryWrapper<SystemUsers>()
                .eq(SystemUsers::getLoginName, param.getLoginName())
                .ne(param.getId() != null, SystemUsers::getId, param.getId()));
        return userNum;
    }

    /**
     *  初始化密码
     * @param id
     */
    public void initPassword(Long id) {
        SystemUsers user = systemUsersMapper.selectById(id);
        if (null == user) {
            throw new LogicException("该用户不存在");
        }
        // 设置密码
        SystemParameter passwordP = systemParameterService.getByKey(SystemParamterContants.USER_DEFALUT_PASSWORD);
        if(passwordP==null){
            throw new LogicException("无法获得参数:"+SystemParamterContants.USER_DEFALUT_PASSWORD);
        }
        String encPassword= AuthenticateProvider.encodeLoginPasswordOnMd5(passwordP.getPvalue(), user.getLoginName());
        user.setPassword(encPassword);
        systemUsersMapper.updateById(user);
    }

    public List<SystemUserExportResult> export(SystemUserQueryAllParam param) {
        List<SystemUserExportResult> users=systemUsersMapper.export(param);
        return users;
    }

    /**
     * 根据租户id获取用户信息
     * @param id 租户id
     * @return 用户信息
     */
    @TenantIgnore
    public SystemUsers getTenantAdminByTenantId(Long id) {
        return systemUsersMapper.selectOne(Wrappers.lambdaQuery(SystemUsers.class)
               .eq(SystemUsers::getTenantId, id)
               .eq(SystemUsers::getType, SystemUsers.UserType.TENANT_ADMIN.getCode()));
    }
}
